﻿namespace Nop.Plugin.Payments.UsaEpay
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    /// <summary>
    /// The USA ePay token.
    /// </summary>
    public class UsaEpayToken : ueSecurityToken
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="UsaEpayToken"/> class.
        /// </summary>
        /// <param name="usaEpayPaymentSettings">
        /// The USA E-pay payment settings.
        /// </param>
        public UsaEpayToken(UsaEpayPaymentSettings usaEpayPaymentSettings)
        {
            var token = new ueSecurityToken
                            {
                                SourceKey = usaEpayPaymentSettings.SourceKey, 
                            };

            string pin = usaEpayPaymentSettings.Pin; // pin assigned to source

            var hash = new ueHash { Type = "md5", Seed = Guid.NewGuid().ToString() };

            string prehashvalue = string.Concat(token.SourceKey, hash.Seed, pin); // combine data into single string
            hash.HashValue = this.GenerateHash(prehashvalue); // generate hash

            token.PinHash = hash; // add hash value to token

            this.Token = token;
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the token.
        /// </summary>
        public ueSecurityToken Token { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// The generate hash.
        /// </summary>
        /// <param name="input">
        /// The input.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string GenerateHash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            var md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            var generatedHash = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            foreach (var t in data)
            {
                generatedHash.Append(t.ToString("x2"));
            }

            // Return the hexadecimal string.
            return generatedHash.ToString();
        }

        #endregion
    }
}